/** \file
* Declarations for the XML web reader class.
* This file is part of Chorus, available at
* http://code.google.com/p/chorus-twitter/ . This file and all associated files
* and derivative works are bound by the terms of the LGPL 3.0 license,
* available at http://www.gnu.org/licenses/lgpl-3.0-standalone.html .
* \par Subversion URL:
* \$URL: http://chorus-twitter.googlecode.com/svn/branches/cpp/src/xml/XmlUrlSource.hpp $
* \version \$Rev: 153 $
* \date    \$Date: 2010-04-06 07:43:42 +0000 (Tue, 06 Apr 2010) $
*/

#pragma once

#include "system/CurlGlob.hpp"
#include "system/Mutex.hpp"
#include "system/Thread.hpp"
#include "xml/XmlSource.hpp"

/// The XML web reader class. Uses curl for portability.
class XmlUrlSource : public XmlSource
{
public:
	/// The constructor.
	/// \param treeInit     The XmlTree to which we send parse events.
	/// \param pathInit     The path to the file.
	/// \param curlGlobInit A pointer to the curl globals object to use.
	XmlUrlSource(XmlTree *treeInit, const char *pathInit,
		CurlGlob *curlGlobInit);
	/// The destructor.
	virtual ~XmlUrlSource();

private:
	/// Fetch the data from the source.
	/// \return True for success.
	virtual bool perform();

private:
	/// The static curl callback.
	/// \param ibuffer The data.
	/// \param size    The data element size.
	/// \param nmemb   The data length.
	/// \param userp   The this-pointer.
	/// \return The number of bytes processed if successful, or -1 otherwise.
	static size_t curlWriteData(void *ibuffer, size_t size, size_t nmemb,
		void *userp);

	/// Hand the XML data from curl to the XML processing thread. Uses mutex
	/// interlocking.
	/// \param ibuffer The data.
	/// \param ibytes  The data length.
	/// \return The number of bytes processed if successful, or -1 otherwise.
	size_t xmlHandover(char *ibuffer, size_t ibytes);

	/// The XML processing thread callback function.
	/// \return True for success.
	bool xmlProcess();

private:
	/// The curl easy pointer.
	CURL *curleasy;
	/// The curl globals pointer.
	CurlGlob *const curlglob;

	/// The XML processing mutex.
	Mutex xmlmutex;
	/// The curl mutex.
	Mutex curlmutex;

	/// The XML processing thread.
	Thread xmlthread;

	/// The incoming XML buffer.
	char *buffer;
	/// The size of the data in the XML buffer.
	size_t bytes;
	/// The allocated size of the XML buffer.
	size_t bytesAllocated;
};
